package org.binglan.youziyuepai.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.binglan.youziyuepai.controller.base.BasicController;
import org.binglan.youziyuepai.entity.*;
import org.binglan.youziyuepai.enums.code.AllowEnum;
import org.binglan.youziyuepai.enums.code.StatusEnum;
import org.binglan.youziyuepai.form.ActivityForm;
import org.binglan.youziyuepai.form.ActivityToOccupationForm;
import org.binglan.youziyuepai.service.*;
import org.binglan.youziyuepai.utils.ResponseVoUtils;
import org.binglan.youziyuepai.vo.ActivityApplyVo;
import org.binglan.youziyuepai.vo.ActivityVo;
import org.binglan.youziyuepai.vo.PageVo;
import org.binglan.youziyuepai.vo.ResponseVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @description:
 * @author: sanjin
 * @date: 2019/4/9 19:57
 */
@Api(tags = "活动相关接口")
@RestController
@RequestMapping("/avtivity")
public class ActivityController extends BasicController {
    @Autowired
    ActivityService activityService;

    @Autowired
    FastFileStorageClient storageClient;

    @Autowired
    OccupationService occupationService;

    @Autowired
    ImageService imageService;

    @Autowired
    ActivityToUserService activityToUserService;

    @Autowired
    UserService userService;

    @Autowired
    UserContactWayService userContactWayService;

    @ApiOperation(value = "创建活动接口", notes = "创建活动接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string")
    })
    @PostMapping(value = "")
    public ResponseVo createActivity(@RequestBody @Valid ActivityForm activityForm,
                                     BindingResult bindingResult) {
        String userId = this.getUserIdByAuth();
        // 验证参数
        if (bindingResult.hasErrors()) {
            return ResponseVoUtils.error(bindingResult);
        }
        List<ActivityToOccupationForm> occupationNumList = activityForm.getOccupations();
        List<ActivityToOccupation> activityToOccupationList = new ArrayList<>();
        List<ActivityToImage> activityToImageList = new ArrayList<>();
        Activity activity = new Activity();
        activity.setUserId(userId);

        // 判断图片id是否存在
        List<String> imageIds = activityForm.getImageIds();
        if (imageIds.size() != 0 && !imageService.isExistsIds(imageIds)) {
            return ResponseVoUtils.error("图片id不存在");
        }
        imageIds.forEach(imageId -> {
            ActivityToImage activityToImage = new ActivityToImage();
            activityToImage.setImageId(imageId);
            activityToImageList.add(activityToImage);
        });

        // 填充活动
        BeanUtils.copyProperties(activityForm, activity);

        // 判断职业id是否存在
        List<Integer> occupationIds = occupationNumList.stream()
                .map(ActivityToOccupationForm::getOccupationId)
                .collect(Collectors.toList());
        if (!occupationService.isExistsIds(occupationIds)) {
            return ResponseVoUtils.error("您上传的职业id不存在");
        }

        // 填充职业人数
        occupationNumList.forEach(item -> {
            ActivityToOccupation activityToOccupation = new ActivityToOccupation();
            activityToOccupation.setNum(item.getNum());
            activityToOccupation.setOccupationId(item.getOccupationId());
            activityToOccupationList.add(activityToOccupation);
        });

        Boolean saveActivity = activityService.saveActivity(activityToOccupationList, activityToImageList, activity);
        if (!saveActivity) return ResponseVoUtils.error("发布活动失败，请重新发布");
        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "获取活动信息接口", notes = "获取活动信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping(value = "")
    public ResponseVo getActivityInfo(Integer activityId) {
        if (activityId == null) {
            return ResponseVoUtils.error("activityId 不能为空");
        }
        ActivityVo activityVo = activityService.queryActivityVoById(activityId);

        return ResponseVoUtils.success(activityVo);
    }


    @ApiOperation(value = "删除活动信息接口", notes = "删除活动信息接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "query", dataType = "string")
    })
    @DeleteMapping(value = "")
    public ResponseVo deleteActivity(Integer activityId) {
        if (activityId == null) {
            return ResponseVoUtils.error("activityId 不能为空");
        }
        String UserId = this.getUserIdByAuth();

        boolean isDelete = activityService.deleteActivityByActivityId(activityId, UserId);
        if (!isDelete)
            return ResponseVoUtils.error("你不是该活动的发布者");
        return ResponseVoUtils.success();
    }


    @ApiOperation(value = "用户加入活动接口", notes = "用户加入活动接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "occupationId", value = "职业id", required = true, paramType = "query", dataType = "string")
    })
    @PostMapping(value = "/join")
    public ResponseVo userJoinActivity(Integer activityId, Integer occupationId) {
        String userId = this.getUserIdByAuth();
        activityService.addUserToActivity(userId, activityId, occupationId);
        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "用户退出活动接口", notes = "用户退出活动接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "activityId", value = "活动id", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @PostMapping(value = "/quit")
    public ResponseVo userQuitActivity(Integer activityId) {
        String userId = this.getUserIdByAuth();
        activityService.quitUserToActivity(userId, activityId);
        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "获取活动信息接口(Page)", notes = "获取活动信息接口(Page)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "当前页", required = true, paramType = "query", dataType = "string"),
            @ApiImplicitParam(name = "size", value = "每页数据数量", required = true, paramType = "query", dataType = "string")
    })
    @GetMapping(value = "/list")
    public ResponseVo listActivityInfo(@RequestParam(value = "page", defaultValue = "1") Integer page,
                                       @RequestParam(value = "size", defaultValue = "5") Integer size) {

        Page<Activity> activityPage = new Page<>(page, size);

        PageVo<ActivityVo> pageVo = activityService.queryActivityVoByPage(activityPage, AllowEnum.ALLOW.getCode());

        return ResponseVoUtils.success(pageVo);
    }

    @ApiOperation(value = "接受用户加入活动请求", notes = "接受用户加入活动请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "applyId", value = "活动请求id", required = true, paramType = "query", dataType = "string"),
    })
    @GetMapping(value = "/apply/accept")
    public ResponseVo acceptActivityApply(Integer applyId) {
        String userId = this.getUserIdByAuth();

        activityToUserService.changeActivityToUserStatus(userId, applyId, StatusEnum.ACCEPT.getCode());

        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "拒绝用户加入活动请求", notes = "拒绝用户加入活动请求接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
            @ApiImplicitParam(name = "applyId", value = "活动请求id", required = true, paramType = "query", dataType = "string"),
    })
    @GetMapping(value = "/apply/refuse")
    public ResponseVo refuseActivityApply(Integer applyId) {
        String userId = this.getUserIdByAuth();

        activityToUserService.changeActivityToUserStatus(userId, applyId, StatusEnum.REFUSE.getCode());

        return ResponseVoUtils.success();
    }

    @ApiOperation(value = "获取用户收到的活动申请", notes = "获取用户收到的活动申请接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/apply/receive")
    public ResponseVo getReceiveActivityApply() {
        String userId = this.getUserIdByAuth();
        List<ActivityToUser> activityToUsers = activityToUserService.queryActivityToUsersByReceiveUserId(userId);
        List<ActivityApplyVo> activityApplyVos = new ArrayList<>(activityToUsers.size());

        activityToUsers.forEach(atu -> {
            ActivityApplyVo vo = new ActivityApplyVo();
            vo.setUserVo(userService.queryUserVoByUserId(atu.getUserId()));
            vo.setOccupation(occupationService.queryOccupationById(atu.getOccupationId()));
            vo.setActivityVo(activityService.queryActivityVoById(atu.getActivityId()));
            vo.setUsetContactWayVo(userContactWayService.queryUserContactWayVoByUserId(atu.getUserId()));
            vo.setActivityToUser(atu);
            activityApplyVos.add(vo);
        });

        return ResponseVoUtils.success(activityApplyVos);
    }

    @ApiOperation(value = "获取用户发送的活动申请", notes = "获取用户发送的活动申请")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/apply/send")
    public ResponseVo getSendActivityApply() {
        String userId = this.getUserIdByAuth();
        List<ActivityToUser> activityToUsers = activityToUserService.queryActivityToUsersBySendUserId(userId);
        List<ActivityApplyVo> activityApplyVos = new ArrayList<>(activityToUsers.size());

        activityToUsers.forEach(atu -> {
            ActivityApplyVo vo = new ActivityApplyVo();
            Activity activity = activityService.queryActivityById(atu.getActivityId());
            vo.setUserVo(userService.queryUserVoByUserId(activity.getUserId()));
            vo.setOccupation(occupationService.queryOccupationById(atu.getOccupationId()));
            vo.setActivityVo(activityService.queryActivityVoById(atu.getActivityId()));
            vo.setActivityToUser(atu);
            activityApplyVos.add(vo);
        });

        return ResponseVoUtils.success(activityApplyVos);
    }

    @ApiOperation(value = "获取用户已经参加的活动(活动发起人已经接受)", notes = "获取用户已经参加的活动(活动发起人已经接受)")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "Authorization", value = "认证token", required = true, paramType = "header", dataType = "string"),
    })
    @GetMapping(value = "/getUserJoinActivitys")
    public ResponseVo getUserJoinActivitys() {
        String userId = this.getUserIdByAuth();
        List<ActivityVo> userJoinActivitys = activityService.getUserJoinActivitys(userId);

        return ResponseVoUtils.success(userJoinActivitys);
    }
}
